<?php

namespace App\Http\Controllers;
use DB;
use Hash;
use App\User as User;
use App\Models\Project_info as Project_info;
use App\Models\Selection as Selection;
use App\Models\Fee as Fee;
use App\Models\Report as Report;
use App\Models\Report_info as Report_info;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

session_start();
#学生端控制器
class StdController extends Controller
{

        
    
	########################选择项目############################################
    public function index(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }


        $select=Selection::find($_SESSION['sid']);
        if(empty($select)){
            $data=Project_info::where('editable','=',0)->get();
            if(!isset($_GET['submit'])){
                return view('std/home',['data'=>$data]);
            }
            else{
                #处理表单信息  
                $name=$_GET['name'];
                $support_type=$_GET['support_type'];
                $pub_person=$_GET['pub_person'];
                $college=$_GET['college'];
                $pro_year=$_GET['pro_year'];
               
                $data=Project_info::all();
                $data='select * from v_project_teas where 1 and editable = 0 ';
                if(!empty($name))
                    $data=$data.'and pname like \'%'.$name.'%\' ';
               /* print_r($data);*/
                if(!empty($support_type))
                    $data=$data.'and support_type = \''.$support_type.'\' ';
                if(!empty($pub_person))
                    $data=$data.'and name like \'%'.$pub_person.'%\' ';
                if(!empty($college))
                    $data=$data.'and college = \''.$college.'\' ';
                if(!empty($pro_year))
                    $data=$data.'and year = \''.$pro_year.'\' ';
                $data=$data.';';
                $dataset=DB::select($data);
                return view('std/home',['data'=>$dataset]);
            }
        }
        else{
            $data=Project_info::find($select->pid);
            $this->showMessage('已经选好项目，返回查看项目运转。');
            return view('project/std_detail',['data'=>$data]);
        }

    }

    public function isNull(){
        $data=$this->getProjectInfo();
        if($data->pid==11111111){
            $data=Project_info::where('editable','=',0)->get();
            $this->showMessage('请先选择项目');
            return view('std/home',['data'=>$data]);
        }
        return true;
    }
    ################################项目运转##############################################
    public function apply(Request $request){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }


        
		if(!isset($_GET['submit'])){

            
        $data=$this->getProjectInfo();
           if($data->pid==11111111){
                $data=Project_info::where('editable','=',0)->get();
                $this->showMessage('请先选择项目');
                return view('std/home',['data'=>$data]);
            }
            else
                return view('project/std_detail',['data'=>$data]);  
            
            

        }
    	else
        {
            $success=Selection::store($request);
            $data=$this->getProjectInfo();
            Project_info::setState($data->pid,1);   #修改项目状态码,等待确认组员1
            if($success==true)
                $data=Project_info::find($request->input('pid'));
            return view('project/std_detail',['data'=>$data]);
    	}

    }
    ##取消申请
    public function delete_apply(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }

        $sid=$_SESSION['sid'];
        Selection::destroy($sid);
        $data=Project_info::find(11111111);
        return view('std/apply',['data'=>$data]);
    }

    ####################开题报告#####################################################
    public function start_report(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }


    $data=$this->getProjectInfo();

        if($data->type>3){
            return $report=$this->init_report(0,'std/start_write');
        }
        else{
            $data=$this->getProjectInfo();
            if($data->pid==11111111){
                $data=Project_info::where('editable','=',0)->get();
                $this->showMessage('请先选择项目');
                return view('std/home',['data'=>$data]);
            }
            else
            #状态码2，等待提交开题报告 ,跳转项目详情页面
            return $this->returnBack('project/std_detail',2);
        }
    }

    #撰写报告,进入初始化报告
    public function start_entry($report_type){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }


        return $report=$this->init_report($report_type,'std/start_write');
    }
    #修改报告
    public function start_write(Request $request){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }

        return $this->submit_report($request,'std/start_write',3);#等待审核开题报告3
    }

	###################中期检查表######################################################
    #总揽页面
    public function mid_report(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }
        


        $data=$this->getProjectInfo();
        if($data->type>5){
            return $report=$this->init_report(1,'std/mid_write');
        }
        else{
            $data=$this->getProjectInfo();
            if($data->pid==11111111){
                $data=Project_info::where('editable','=',0)->get();
                $this->showMessage('请先选择项目');
                return view('std/home',['data'=>$data]);
            }
            else
		      #如状态码4，等待提交中期报告
            return $this->returnBack('project/std_detail',4);
        }
    }

    #撰写报告,进入初始化报告
    public function mid_entry($report_type){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }

        return $report=$this->init_report($report_type,'std/mid_write');
    }
    #修改报告
    public function mid_write(Request $request){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }

        return $this->submit_report($request,'std/mid_write',5);#等待审核中期检查表5
    }
    
    ############################结题报告###############################################
    public function final_report(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }

        if( !$this->isNull() ){
                return isNull();
            }
        $data=$this->getProjectInfo();
        if($data->type>7){
            return $report=$this->init_report(2,'std/final_write');
        }
        else{
             $data=$this->getProjectInfo();
            if($data->pid==11111111){
                $data=Project_info::where('editable','=',0)->get();
                $this->showMessage('请先选择项目');
                return view('std/home',['data'=>$data]);
            }
            else
            #状态码3,等待提交结题报告
            return $this->returnBack('project/std_detail',6);
        }
    }
    #撰写报告,进入初始化报告
    public function final_entry($report_type){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }
        return $report=$this->init_report($report_type,'std/final_write');
    }
    #修改报告
    public function final_write(Request $request){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }
        return $this->submit_report($request,'std/final_write',7);#等待审核结题报告7
    }
   
    #####################经费预算######################################################
    public function fees_predict(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }
        
        $data=$this->getProjectInfo();
        if($data->pid==11111111){
            $data=Project_info::where('editable','=',0)->get();
            $this->showMessage('请先选择项目');
            return view('std/home',['data'=>$data]);
        }
        else{

    		#如项目未批准，返回主页,状态码2
            return $this->returnBack('std/modify_fees',2); 
        }
    }

    #修改经费
    public function modify_fees(Request $request){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }
                

                $temp=Selection::find($_SESSION['sid']);
                if(!isset($_POST['submit']))
                {
                    #显示上次修改内容
                    if(empty($temp)){
                        #没有申报项目
                        $temp=Project_info::find(11111111);
                        return view('std/std_select',['data'=>$temp]);
                    }     
                    else{
                        $fees=Fee::find($temp->pid);
                        if(empty($fees)){
                            #没有做过经费预算
                            $fees=Fee::init($temp->pid);
                        }
                        return view('std/modify_fees',['data'=>$fees]);
                    }
                }
                else{
                    #更新经费预算
                    $success=Fee::modify($request,$temp->pid);
                    $fees=Fee::find($temp->pid);
                    if($success)
                        $this->showMessage('成功修改预算');
                    else
                        $this->showMessage('出现故障，请联系工作人员。');
                    return  view('std/modify_fees',['data'=>$fees]);
                }

        
    
    }
 	#########################成果跟踪##############################################
    public function result_check(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }


        $data=$this->getProjectInfo();
        if($data->type>9){
            return $report=$this->init_report(3,'std/result_track');
        }
        else{

            $data=$this->getProjectInfo();
         if($data->pid==11111111){
                $data=Project_info::where('editable','=',0)->get();
                $this->showMessage('请先选择项目');
                return view('std/home',['data'=>$data]);
            }
            else
           return $this->returnBack('project/std_detail',8);
        }
    }
    #撰写报告,进入初始化报告
    public function result_entry(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }



        return $report=$this->init_report(3,'std/result_track');
    }

    public function result_track(Request $request){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }


        #存储表单信息 
        Report_info::store($request);
        #存储上传文件
        $this->uploads_file($request);
        $report=Report::find($request->rid);
        Project_info::setState($report->pid,9);  #修改项目状态码,等待审核成果跟踪9
        $this->showMessage('提交成功');
        return view('std/result_track',['report'=>$report]);
    	
    }
    ###########################展板提交############################################
    public function panels_check(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }


 
        $data=$this->getProjectInfo();
        if($data->type>11){
            return $report=$this->init_report(4,'std/panels_submit');
        }
        else{
             $data=$this->getProjectInfo();
         if($data->pid==11111111){
                $data=Project_info::where('editable','=',0)->get();
                $this->showMessage('请先选择项目');
                return view('std/home',['data'=>$data]);
            }
            else
            return $this->returnBack('project/std_detail',10);
        }
    }
    #撰写报告,进入初始化报告
    public function panels_entry(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }


        return $report=$this->init_report(4,'std/panels_submit');
    }

    public function panels_submit(Request $request){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }


        #存储表单信息 
        Report_info::store($request);
        #存储上传文件
        $this->uploads_file($request);
        $report=Report::find($request->rid);
        Project_info::setState($report->pid,11);  #修改项目状态码,等待审核展板11
        $this->showMessage('提交成功');
        return view('std/panels_submit',['report'=>$report]);
    }

    ##########################收件箱################################################
    public function rec_box(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }


		if(!isset($_GET['submit']))
			return view('std/rec_box');
    	else{
    		#处理表单信息
    	}
    }

    #################################3#发件箱########################################
    public function snd_box(){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }

		if(!isset($_GET['submit']))
			return view('std/snd_box');
    	else{
    		#处理表单信息
    	}
    }

    #########################修改密码#################################################
    public function modify_pwd(Request $request){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }

		if(!isset($_GET['submit']))
			return view('std/modify_pwd');
    	else{
    		#处理表单信息
            $user = User::findOrFail($_SESSION['sid']);

            if (Hash::check($request->input('password'), $user->password)) {
                // 密码匹配...
                $user->fill(['password' => Hash::make($request->new_password)])->save();
                $this->showMessage('成功设置新密码。');
            }
            else{
                $this->showMessage('原密码出错，请重试。');
            }
            return view('std/modify_pwd');
    	}
    }

    #############################修改个人信息##########################################
    public function modify_info(Request $request){
        if(!isset($_SESSION['sid'])){
            return view('/auth/login');
        }
        
        if(!isset($_GET['submit']))
        {
            $data=User::find($_SESSION['sid']);
            return view('std/modify_info',['data'=>$data]);
        }
        else
        {
            #处理表单信息
            $success=User::modify_info($request);
            $data=User::find($_SESSION['sid']);
            if($success==true)
                $this->showMessage('成功修改个人信息。');
            else
                $this->showMessage('修改信息出错，请重试。');
            return view('std/modify_info',['data'=>$data]);
        }
    }


    ################参数:显示信息，返回页面#############################
    public function showMessage($show_info){
            echo '<script type="text/javascript">
                    alert("'.$show_info.'");
                </script>';
    }
    ###############################获取项目信息###########################
    public function getProjectInfo(){
        $temp=Selection::find($_SESSION['sid']);  
        if(empty($temp))
            return Project_info::find(11111111);
        else
            return Project_info::find($temp->pid);
    }

    ##########################初始化报告信息###############################
    public function init_report($report_type,$showPage){

        $data=$this->getProjectInfo();
        $reports=Report::where('pid', '=',$data->pid)->where('report_type','=',$report_type)->get();
        if($reports->count()!=0)
            $report=$reports[0];
        else
        {
            $report=Report::init($data->pid,$report_type);
            $report_info=Report_info::init($report->rid);
        }

        return view($showPage,['report'=>$report]);
    }

    ##########################提交报告信息###############################
    public function submit_report(Request $request,$showPage,$sid){
        $rid=$request->input('rid');
        

        #存储上传文件
        $this->uploads_file($request);

        $tempName=$request->input('file');

        $tempReport=Report_info::find($rid);
        if(empty($tempName) && $tempReport->attachmentname==""){
            $this->showMessage('未提交附件,请及时补交');
        }


        //保存报告信息
        Report_info::store($request);
        
        if(empty($tempName) && $tempReport->attachmentname!=""){
            Report_info::storeAttach($rid,$tempReport->attachmentname,$tempReport->attachmentpath);
        }
        

        $result=Report::find($rid);
        Project_info::setState($result->pid,$sid);              #修改项目状态码
        $this->showMessage("成功保存报告内容。");
        return view($showPage,['report'=>$result]);
    }

    ###############################上传文件###############################
    public function uploads_file(Request $request){
        #处理表单信息
        if($request->hasFile('file'))
        {
            $file = $request->file('file');
            $clientName = $file -> getClientOriginalName();
            #$tempName = $file ->getFileName();
            #$realPath = $file -> getRealPath();
            # $mimeTye = $file -> getMimeType();
            $extension = $file -> getClientOriginalExtension(); //上传文件的后缀.
            $newName = md5(date('ymdhis').$clientName).".".$extension;
            $path = $file -> move(app_path().'\storage\uploads',$newName);
            
            Report_info::storeAttach($request->rid,$clientName,$newName);
        }
        else{
           # $this->showMessage('未提交附件,请及时补交');
        }
    }

    ######################文件下载######################################
    public function downloads($name,$real){

        $file_dir = app_path().'\storage\uploads\\';    
         echo $file_dir;
        if (!file_exists($file_dir.$name)){
            header("Content-type: text/html; charset=utf-8");
            echo "File not found!";
            exit(); 
        } else {
            $file = fopen($file_dir.$name,"r"); 
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length: ".filesize($file_dir . $name));
            Header("Content-Disposition: attachment; filename=".$real);

            ob_clean();  
            flush();  
            readfile($file_dir.$name);  
        }
    }
  
    ####################流程控制：回跳函数##############################
    #如果当前项目状态码小于本流程状态码，说明还未执行到此项内容，返回主页。
    #如果当前项目状态码大于本流程状态码，则可以进入这个环节。
    public function returnBack($page,$id){
        $project=$this->getProjectInfo();
        if($project->type<$id)
        {
            #$project=Project_info::where('editable','=',0)->get();
            $this->showMessage('暂未运行到此项流程，请耐心等候。');
            return view('project/std_detail',['data'=>$project]);
        }
        else{
            return view($page,['data'=>$project]);
        }
            
    }

}
